package 多线程;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zhang lei
 * @Date 2022-01-08 11:14
 */
public class ProducerAndConsumer {

    private ReentrantLock lock = new ReentrantLock();
    private Condition producerCondition = lock.newCondition();
    private Condition consumerCondition = lock.newCondition();
    private int maxSum = 10;
    private int curSum = 0;

    public static void main(String[] args) {
        ProducerAndConsumer test = new ProducerAndConsumer();

        //注意这里这个 test.new    搞了半天
        new Thread(test.new Producer1(), "生产者1").start();
        new Thread(test.new Producer1(), "生产者2").start();
        new Thread(test.new Consumer1(), "消费者1").start();
        new Thread(test.new Consumer1(), "消费者2").start();

    }

     class Producer1 implements Runnable{

        @Override
        public void run() {
            for (int i = 0;i<10;i++) {
                lock.lock();

                try {
                    while (curSum>=maxSum) {
                        System.out.println("生产满了");
                        producerCondition.await();
                    }
                    curSum++;
                    System.out.println(Thread.currentThread().getName() + "生产了1个, 当前" + curSum);
                    consumerCondition.signalAll();
                } catch (Exception e) {

                }
                finally {
                    lock.unlock();
                }
            }
        }
    }

    class Consumer1 implements Runnable{

        @Override
        public void run() {
            for (int i =0;i<10;i++) {
                lock.lock();

                try {
                    while (curSum<=0) {
                        System.out.println("没有货品了");
                        consumerCondition.await();
                    }
                    curSum--;
                    System.out.println(Thread.currentThread().getName() + "消费了1个, 当前" + curSum);
                    producerCondition.signalAll();
                } catch (Exception e) {

                }
                finally {
                    lock.unlock();
                }
            }
        }
    }

}



